import React, { memo } from 'react';
import {
  ModalForm,
  ModalFormProps,
  ProFormGroup,
  ProFormList,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-form';
import { Tabs, message } from 'antd';
import { EnvLocation } from '../../interface';
import { saveEnvLocation } from '@/api';
import type { ActionType } from '@ant-design/pro-table';

type Props = {
  id?: string;
  envLocation: EnvLocation[];
  action?: ActionType;
  children?: JSX.Element;
};

const locations: EnvLocation[] = [
  {
    env: 'dev',
    host: '',
    path: '',
    sub: '',
  },
  {
    env: 'fat',
    host: '',
    path: '',
    sub: '',
  },
  {
    env: 'sit',
    host: '',
    path: '',
    sub: '',
  },
  {
    env: 'prod',
    host: '',
    path: '',
    sub: '',
  },
];

const EnvLocationCard = () => {
  return (
    <ProFormGroup>
      <ProFormText width="xs" name="env" readonly />
      <ProFormSelect
        label="子域名"
        name={'sub'}
        width="xs"
        options={[
          {
            value: 'bill',
            label: 'bill',
          },
          {
            value: 'atm',
            label: 'atm',
          },
        ]}
      />
      <ProFormSelect
        label="主域名"
        name={'host'}
        width="md"
        options={[
          {
            value: 'bill.com',
            label: 'bill.com',
          },
          {
            value: 'atm.com',
            label: 'atm.com',
          },
        ]}
      />
      <ProFormText label="默认路径" name={'path'} width="xs" />
    </ProFormGroup>
  );
};

const EnvLocationComponent = (props: Props) => {
  const { action, envLocation = locations, children, id } = props;

  return (
    <ModalForm<ModalFormProps>
      title="设置环境链接"
      trigger={children}
      onFinish={async (formData) => {
        try {
          await saveEnvLocation({ ...formData });
          message.success('设置成功');

          action?.reload();

          return true;
        } catch (error) {
          message.error(error.message);
        }
      }}
      initialValues={{
        id,
        envLocation,
      }}
    >
      <React.Fragment>
        <ProFormText name="id" hidden />
        <ProFormList
          name="envLocation"
          itemRender={(dom, listData) => {
            return dom.listDom;
          }}
          creatorButtonProps={false}
        >
          <EnvLocationCard />
        </ProFormList>
      </React.Fragment>
    </ModalForm>
  );
};

export default memo(EnvLocationComponent, (prevProps, nextProps) => {
  return prevProps.id === nextProps.id;
});
